import UIKit
import AVFoundation
import Photos

class CameraViewController: UIViewController {
    
    // MARK: - UI Elements
    private var previewView: UIView!
    private var captureButton: UIButton!
    private var filterCollectionView: UICollectionView!
    private var photoLibraryButton: UIButton!
    private var switchCameraButton: UIButton!
    private var filterNameLabel: UILabel!
    
    // MARK: - Camera Properties
    private var captureSession: AVCaptureSession!
    private var videoPreviewLayer: AVCaptureVideoPreviewLayer!
    private var photoOutput: AVCapturePhotoOutput!
    private var currentCameraPosition: AVCaptureDevice.Position = .back
    
    // MARK: - Filter Properties
    private let filterEngine = FilterEngine()
    private var currentFilterIndex = 0
    private let filterNames = ["原图", "复古", "清新", "暖阳", "冷调", "胶片", "黑白", "柔焦"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupCamera()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if captureSession?.isRunning == false {
            DispatchQueue.global(qos: .userInitiated).async {
                self.captureSession.startRunning()
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if captureSession?.isRunning == true {
            DispatchQueue.global(qos: .userInitiated).async {
                self.captureSession.stopRunning()
            }
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 确保拍照按钮可见且在最顶层
        view.bringSubviewToFront(captureButton)
        print("🔍 viewDidAppear - 按钮frame: \(captureButton.frame), superview: \(captureButton.superview != nil)")
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        videoPreviewLayer?.frame = previewView.bounds
        
        // Debug: Check button frame after layout
        print("🔍 Layout完成，拍照按钮frame: \(captureButton.frame), isUserInteractionEnabled: \(captureButton.isUserInteractionEnabled)")
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        view.backgroundColor = .black
        
        // Create preview view
        previewView = UIView()
        previewView.backgroundColor = .black
        previewView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(previewView)
        
        // Create filter collection view
        setupFilterCollectionView()
        
        // Create professional capture button - VSCO/DAZZ style
        captureButton = UIButton(type: .custom)
        captureButton.backgroundColor = .clear
        captureButton.layer.cornerRadius = 40
        captureButton.layer.borderWidth = 4
        captureButton.layer.borderColor = UIColor.white.cgColor
        captureButton.translatesAutoresizingMaskIntoConstraints = false
        
        // Create inner white circle - professional camera style
        let innerCircle = UIView()
        innerCircle.backgroundColor = .white
        innerCircle.layer.cornerRadius = 32
        innerCircle.translatesAutoresizingMaskIntoConstraints = false
        innerCircle.isUserInteractionEnabled = false
        captureButton.addSubview(innerCircle)
        
        // Inner circle constraints
        NSLayoutConstraint.activate([
            innerCircle.centerXAnchor.constraint(equalTo: captureButton.centerXAnchor),
            innerCircle.centerYAnchor.constraint(equalTo: captureButton.centerYAnchor),
            innerCircle.widthAnchor.constraint(equalToConstant: 64),
            innerCircle.heightAnchor.constraint(equalToConstant: 64)
        ])
        
        // 确保按钮完全可交互
        captureButton.isUserInteractionEnabled = true
        captureButton.isEnabled = true
        
        // 添加触摸事件和动画效果
        captureButton.addTarget(self, action: #selector(captureButtonTapped), for: .touchUpInside)
        captureButton.addTarget(self, action: #selector(captureButtonTouchDown), for: .touchDown)
        captureButton.addTarget(self, action: #selector(captureButtonTouchUp), for: .touchUpInside)
        captureButton.addTarget(self, action: #selector(captureButtonTouchUp), for: .touchUpOutside)
        
        view.addSubview(captureButton)
        
        // 确保按钮在所有视图之上
        view.bringSubviewToFront(captureButton)
        print("🔍 拍照按钮已创建")
        
        // Create photo library button - Professional VSCO/DAZZ style
        photoLibraryButton = UIButton(type: .system)
        let libraryIcon = UIImage(systemName: "photo.stack", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .medium))
        photoLibraryButton.setImage(libraryIcon, for: .normal)
        photoLibraryButton.tintColor = .white
        photoLibraryButton.backgroundColor = UIColor.black.withAlphaComponent(0.4)
        photoLibraryButton.layer.cornerRadius = 22
        photoLibraryButton.layer.borderWidth = 1
        photoLibraryButton.layer.borderColor = UIColor.white.withAlphaComponent(0.4).cgColor
        photoLibraryButton.translatesAutoresizingMaskIntoConstraints = false
        photoLibraryButton.addTarget(self, action: #selector(photoLibraryButtonTapped), for: .touchUpInside)
        
        // Add professional touch effects
        photoLibraryButton.addTarget(self, action: #selector(photoLibraryButtonTouchDown), for: .touchDown)
        photoLibraryButton.addTarget(self, action: #selector(photoLibraryButtonTouchUp), for: .touchUpInside)
        photoLibraryButton.addTarget(self, action: #selector(photoLibraryButtonTouchUp), for: .touchUpOutside)
        
        view.addSubview(photoLibraryButton)
        
        // Create switch camera button - Professional VSCO/DAZZ style
        switchCameraButton = UIButton(type: .system)
        let switchIcon = UIImage(systemName: "camera.rotate", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .medium))
        switchCameraButton.setImage(switchIcon, for: .normal)
        switchCameraButton.tintColor = .white
        switchCameraButton.backgroundColor = UIColor.black.withAlphaComponent(0.4)
        switchCameraButton.layer.cornerRadius = 22
        switchCameraButton.layer.borderWidth = 1
        switchCameraButton.layer.borderColor = UIColor.white.withAlphaComponent(0.4).cgColor
        switchCameraButton.translatesAutoresizingMaskIntoConstraints = false
        switchCameraButton.addTarget(self, action: #selector(switchCameraButtonTapped), for: .touchUpInside)
        
        // Add professional touch effects
        switchCameraButton.addTarget(self, action: #selector(switchCameraButtonTouchDown), for: .touchDown)
        switchCameraButton.addTarget(self, action: #selector(switchCameraButtonTouchUp), for: .touchUpInside)
        switchCameraButton.addTarget(self, action: #selector(switchCameraButtonTouchUp), for: .touchUpOutside)
        
        view.addSubview(switchCameraButton)
        
        // Create filter name label
        filterNameLabel = UILabel()
        filterNameLabel.text = FilterType.allCases[currentFilterIndex].name
        filterNameLabel.textColor = .white
        filterNameLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        filterNameLabel.textAlignment = .center
        filterNameLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        filterNameLabel.layer.cornerRadius = 8
        filterNameLabel.clipsToBounds = true
        filterNameLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(filterNameLabel)
        
        // Setup constraints
        NSLayoutConstraint.activate([
            // Preview view constraints
            previewView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            previewView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            previewView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            previewView.bottomAnchor.constraint(equalTo: filterCollectionView.topAnchor, constant: -10),
            
            // Filter collection view constraints
            filterCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            filterCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            filterCollectionView.bottomAnchor.constraint(equalTo: captureButton.topAnchor, constant: -20),
            filterCollectionView.heightAnchor.constraint(equalToConstant: 100),
            
            // Capture button constraints - Larger professional style
            captureButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            captureButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30),
            captureButton.widthAnchor.constraint(equalToConstant: 80),
            captureButton.heightAnchor.constraint(equalToConstant: 80),
            
            // Photo library button constraints - Refined size
            photoLibraryButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30),
            photoLibraryButton.centerYAnchor.constraint(equalTo: captureButton.centerYAnchor),
            photoLibraryButton.widthAnchor.constraint(equalToConstant: 44),
            photoLibraryButton.heightAnchor.constraint(equalToConstant: 44),
            
            // Switch camera button constraints - Refined size
            switchCameraButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30),
            switchCameraButton.centerYAnchor.constraint(equalTo: captureButton.centerYAnchor),
            switchCameraButton.widthAnchor.constraint(equalToConstant: 44),
            switchCameraButton.heightAnchor.constraint(equalToConstant: 44),
            
            // Filter name label constraints
            filterNameLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            filterNameLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
            filterNameLabel.widthAnchor.constraint(equalToConstant: 120),
            filterNameLabel.heightAnchor.constraint(equalToConstant: 32)
        ])
    }
    
    private func setupFilterCollectionView() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 80, height: 90)
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        layout.sectionInset = UIEdgeInsets(top: 5, left: 16, bottom: 5, right: 16)
        
        filterCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        filterCollectionView.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        filterCollectionView.delegate = self
        filterCollectionView.dataSource = self
        filterCollectionView.showsHorizontalScrollIndicator = false
        filterCollectionView.translatesAutoresizingMaskIntoConstraints = false
        
        // Register cell
        filterCollectionView.register(FilterCell.self, forCellWithReuseIdentifier: "FilterCell")
        view.addSubview(filterCollectionView)
    }
    
    // MARK: - Camera Setup
    private func setupCamera() {
        // Check camera permission first
        checkCameraPermission { [weak self] granted in
            if granted {
                DispatchQueue.main.async {
                    self?.configureCameraSession()
                }
            } else {
                DispatchQueue.main.async {
                    self?.showAlert(message: "需要相机权限才能拍照")
                }
            }
        }
    }
    
    private func checkCameraPermission(completion: @escaping (Bool) -> Void) {
        switch AVCaptureDevice.authorizationStatus(for: .video) {
        case .authorized:
            completion(true)
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { granted in
                completion(granted)
            }
        case .denied, .restricted:
            completion(false)
        @unknown default:
            completion(false)
        }
    }
    
    private func configureCameraSession() {
        captureSession = AVCaptureSession()
        captureSession.sessionPreset = .photo
        
        guard let backCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {
            showAlert(message: "无法访问后置摄像头")
            return
        }
        
        do {
            let input = try AVCaptureDeviceInput(device: backCamera)
            photoOutput = AVCapturePhotoOutput()
            
            if captureSession.canAddInput(input) && captureSession.canAddOutput(photoOutput) {
                captureSession.addInput(input)
                captureSession.addOutput(photoOutput)
                setupLivePreview()
            } else {
                showAlert(message: "相机配置失败")
            }
        } catch {
            showAlert(message: "摄像头设置失败: \(error.localizedDescription)")
        }
    }
    
    private func setupLivePreview() {
        videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        videoPreviewLayer.videoGravity = .resizeAspectFill
        videoPreviewLayer.connection?.videoOrientation = .portrait
        
        previewView.layer.addSublayer(videoPreviewLayer)
        
        DispatchQueue.global(qos: .userInitiated).async {
            self.captureSession.startRunning()
        }
    }
    
    // MARK: - Actions
    @objc private func captureButtonTapped() {
        print("拍照按钮被点击") // Debug log
        
        // Check if camera session is running
        guard captureSession != nil && captureSession.isRunning else {
            showAlert(message: "相机未准备就绪，请重试")
            return
        }
        
        // Check if photo output is available
        guard let photoOutput = photoOutput else {
            showAlert(message: "相机设置错误，请重启应用")
            return
        }
        
        // Create photo settings
        let settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])
        
        // Take photo
        photoOutput.capturePhoto(with: settings, delegate: self)
    }
    
    @objc private func photoLibraryButtonTapped() {
        checkPhotoLibraryPermission { [weak self] granted in
            if granted {
                DispatchQueue.main.async {
                    self?.presentImagePicker()
                }
            }
        }
    }
    
    @objc private func switchCameraButtonTapped() {
        switchCamera()
    }
    
    // MARK: - Capture Button Animation Methods
    @objc private func captureButtonTouchDown() {
        // 专业相机应用的按压动画效果
        UIView.animate(withDuration: 0.1, animations: {
            self.captureButton.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
            self.captureButton.alpha = 0.8
        })
    }
    
    @objc private func captureButtonTouchUp() {
        // 恢复按钮状态
        UIView.animate(withDuration: 0.15, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, animations: {
            self.captureButton.transform = CGAffineTransform.identity
            self.captureButton.alpha = 1.0
        })
    }
    
    // MARK: - Photo Library Button Animation Methods
    @objc private func photoLibraryButtonTouchDown() {
        UIView.animate(withDuration: 0.1, animations: {
            self.photoLibraryButton.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
            self.photoLibraryButton.alpha = 0.7
        })
    }
    
    @objc private func photoLibraryButtonTouchUp() {
        UIView.animate(withDuration: 0.15, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, animations: {
            self.photoLibraryButton.transform = CGAffineTransform.identity
            self.photoLibraryButton.alpha = 1.0
        })
    }
    
    // MARK: - Switch Camera Button Animation Methods
    @objc private func switchCameraButtonTouchDown() {
        UIView.animate(withDuration: 0.1, animations: {
            self.switchCameraButton.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
            self.switchCameraButton.alpha = 0.7
        })
    }
    
    @objc private func switchCameraButtonTouchUp() {
        UIView.animate(withDuration: 0.15, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, animations: {
            self.switchCameraButton.transform = CGAffineTransform.identity
            self.switchCameraButton.alpha = 1.0
        })
    }
    
    // MARK: - Helper Functions
    private func showAlert(message: String) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "确定", style: .default))
            self.present(alert, animated: true)
        }
    }
    
    private func navigateToEditView(with image: UIImage) {
        // Apply current filter to the image
        let selectedFilterType = FilterType.allCases[currentFilterIndex]
        let filteredImage = filterEngine.applyFilter(to: image, filterType: selectedFilterType)
        
        // Save to photo library
        saveImageToPhotoLibrary(filteredImage)
    }
    
    // MARK: - Save to Photo Library
    private func saveImageToPhotoLibrary(_ image: UIImage) {
        PHPhotoLibrary.requestAuthorization { [weak self] status in
            if status == .authorized {
                PHPhotoLibrary.shared().performChanges({
                    PHAssetCreationRequest.creationRequestForAsset(from: image)
                }) { success, error in
                    DispatchQueue.main.async {
                        if success {
                            self?.showAlert(message: "照片已保存到相册！")
                        } else {
                            self?.showAlert(message: "保存失败: \(error?.localizedDescription ?? "未知错误")")
                        }
                    }
                }
            } else {
                DispatchQueue.main.async {
                    self?.showAlert(message: "需要相册访问权限来保存照片")
                }
            }
        }
    }
    
    // MARK: - Camera Functions
    private func switchCamera() {
        captureSession.beginConfiguration()
        
        // Remove current input
        guard let currentInput = captureSession.inputs.first as? AVCaptureDeviceInput else { return }
        captureSession.removeInput(currentInput)
        
        // Switch camera position
        currentCameraPosition = (currentCameraPosition == .back) ? .front : .back
        
        // Add new input
        guard let newCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: currentCameraPosition) else { return }
        
        do {
            let newInput = try AVCaptureDeviceInput(device: newCamera)
            if captureSession.canAddInput(newInput) {
                captureSession.addInput(newInput)
            }
        } catch {
            showAlert(message: "切换摄像头失败: \(error.localizedDescription)")
        }
        
        captureSession.commitConfiguration()
    }
    
    // MARK: - Image Picker
    private func presentImagePicker() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        imagePicker.allowsEditing = false
        present(imagePicker, animated: true)
    }
    
    // MARK: - Permissions
    private func checkPhotoLibraryPermission(completion: @escaping (Bool) -> Void) {
        let status = PHPhotoLibrary.authorizationStatus()
        
        switch status {
        case .authorized:
            completion(true)
        case .denied, .restricted:
            completion(false)
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization { newStatus in
                completion(newStatus == .authorized)
            }
        case .limited:
            completion(true)
        @unknown default:
            completion(false)
        }
    }
}

// MARK: - AVCapturePhotoCaptureDelegate
extension CameraViewController: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        print("拍照委托方法被调用") // Debug log
        
        if let error = error {
            print("拍照错误: \(error.localizedDescription)")
            DispatchQueue.main.async {
                self.showAlert(message: "拍照失败: \(error.localizedDescription)")
            }
            return
        }
        
        guard let imageData = photo.fileDataRepresentation() else {
            print("无法获取图片数据")
            DispatchQueue.main.async {
                self.showAlert(message: "无法获取图片数据")
            }
            return
        }
        
        guard let image = UIImage(data: imageData) else {
            print("无法创建UIImage")
            DispatchQueue.main.async {
                self.showAlert(message: "图片处理失败")
            }
            return
        }
        
        print("拍照成功，开始处理图片")
        DispatchQueue.main.async {
            self.navigateToEditView(with: image)
        }
    }
}

// MARK: - UICollectionViewDataSource & Delegate
extension CameraViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return FilterType.allCases.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FilterCell", for: indexPath) as! FilterCell
        let filterType = FilterType.allCases[indexPath.item]
        cell.configure(with: filterType.name, isSelected: indexPath.item == currentFilterIndex)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        currentFilterIndex = indexPath.item
        
        // Update filter name label
        let selectedFilter = FilterType.allCases[currentFilterIndex]
        filterNameLabel.text = selectedFilter.name
        
        // Add animation for better UX
        UIView.animate(withDuration: 0.2) {
            self.filterNameLabel.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
        } completion: { _ in
            UIView.animate(withDuration: 0.2) {
                self.filterNameLabel.transform = CGAffineTransform.identity
            }
        }
        
        collectionView.reloadData()
    }
}

// MARK: - UIImagePickerControllerDelegate
extension CameraViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        
        if let image = info[.originalImage] as? UIImage {
            // Apply current filter and save to photo library
            let selectedFilterType = FilterType.allCases[currentFilterIndex]
            let filteredImage = filterEngine.applyFilter(to: image, filterType: selectedFilterType)
            saveImageToPhotoLibrary(filteredImage)
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}

// MARK: - Filter Cell
class FilterCell: UICollectionViewCell {
    private let titleLabel = UILabel()
    private let previewView = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupCell()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupCell()
    }
    
    private func setupCell() {
        backgroundColor = UIColor.white.withAlphaComponent(0.1)
        layer.cornerRadius = 8
        
        // Preview view
        previewView.backgroundColor = UIColor.gray.withAlphaComponent(0.3)
        previewView.layer.cornerRadius = 6
        previewView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(previewView)
        
        // Title label
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.systemFont(ofSize: 11, weight: .medium)
        titleLabel.textColor = .white
        titleLabel.numberOfLines = 1
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        addSubview(titleLabel)
        
        NSLayoutConstraint.activate([
            previewView.topAnchor.constraint(equalTo: topAnchor, constant: 8),
            previewView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
            previewView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
            previewView.heightAnchor.constraint(equalToConstant: 50),
            
            titleLabel.topAnchor.constraint(equalTo: previewView.bottomAnchor, constant: 4),
            titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 4),
            titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -4),
            titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -4)
        ])
    }
    
    func configure(with title: String, isSelected: Bool) {
        titleLabel.text = title
        backgroundColor = isSelected ? 
            UIColor.systemBlue.withAlphaComponent(0.3) : 
            UIColor.white.withAlphaComponent(0.1)
        
        layer.borderWidth = isSelected ? 2 : 0
        layer.borderColor = isSelected ? UIColor.systemBlue.cgColor : UIColor.clear.cgColor
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        backgroundColor = UIColor.white.withAlphaComponent(0.1)
        layer.borderWidth = 0
    }
}